package com.java.common.boot.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.java.common.constant.Constants;
import com.java.common.lang.annotation.RequestUser;
import com.java.common.lang.domain.entity.User;

/**
 * 登录用户方法参数解析器
 *
 * @author yilabao
 * @date 2022年5月9日
 */
public class RequestUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String attributeName = null;
        if (parameter.getParameterType() == User.class) {
            attributeName = Constants.LOGIN_USER_ATTRIBUTE;
        } else {
            attributeName = Constants.LOGIN_USER_UID_ATTRIBUTE;
        }
        return webRequest.getAttribute(attributeName, RequestAttributes.SCOPE_REQUEST);
    }

}